package controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import service.FoodService;

@Controller
public class FoodController {
	
	@Autowired
	FoodService service;
	//GetMapping 只接受get提交
	@GetMapping("queryfood")
	public String queryfood(Map map){
		map.put("list", service.queryall() );
		return "index.jsp";
	}
	
	@SuppressWarnings("deprecation")
	@PostMapping("addfood")
	public String addfood(HttpServletRequest request) throws Exception{
		//文件上传第一步强制转换 如果页面没有设置multipart/form-data 会异常
		MultipartHttpServletRequest req=(MultipartHttpServletRequest) request;
		//获得上传的文件  ("填写<input type=files name=files")
		MultipartFile file = req.getFile("files");
		
		InputStream is = file.getInputStream();
		//老套路 死代码
		String path = request.getRealPath("/")+"/images/";
		
		String filename = file.getOriginalFilename();
		filename=filename.substring(filename.lastIndexOf("."));
		filename=System.currentTimeMillis()+filename;
		File file1 = new File(path,filename);
		FileOutputStream fos=new FileOutputStream(file1);
		
		byte[] b=new byte[1024*100];
		int len=0;
		while((len=is.read(b))>0){
			fos.write(b, 0, len);
		}
		fos.close();
		is.close();
		 
		return "redirect:queryfood";
	}

}






